package com.csx.governance.traffic.core.context.webClient;

import com.csx.governance.traffic.core.context.TrafficRequest;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.RequestData;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.http.HttpHeaders;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2023/4/13 10:23
 */
public class TrafficWebClientRequest extends TrafficRequest {

    public TrafficWebClientRequest(Request<RequestDataContext> originRequest) {
        super(originRequest);
    }

    @Override
    public Map<String, String> getSingleValueHeaders() {
        RequestDataContext context = getOriginRequest().getContext();
        RequestData clientRequest = context.getClientRequest();
        HttpHeaders httpHeaders = clientRequest.getHeaders();
        for (Map.Entry<String, List<String>> entry : httpHeaders.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            headers.put(key, values.get(0));
        }
        return headers;
    }

    @Override
    public String getFirstHeader(String name) {
        List<String> headers = getOriginRequest().getContext().getClientRequest().getHeaders().get(name);
        if(CollectionUtils.isEmpty(headers)) {
            return null;
        }
        return headers.get(0);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Request<RequestDataContext> getOriginRequest() {
        return (Request<RequestDataContext>) super.getOriginRequest();
    }

    @Override
    public List<String> getHeaders(String name) {
        return getOriginRequest().getContext().getClientRequest().getHeaders().get(name);
    }


//    @Override
//    public void setHeader(String name, String value) {
//        super.setHeader(name, value);
//        getOriginRequest().getContext().getClientRequest().getHeaders().set(name, value);
//    }

    @Override
    public String getRequestURL() {
        return getOriginRequest().getContext().getClientRequest().getUrl().toString();
    }

    @Override
    public String getRequestURI() {
        return getOriginRequest().getContext().getClientRequest().getUrl().getPath();
    }
}
